import {
	asyncRouterInfo,
	constantRoutes
} from '@/router/routerInfo'

import {
	getUserRouterInfo
} from '@/api/user.js'
/**
 * 判断当前路由是否显示
 * @param menus 可显示菜单id
 * @param route 当前路由
 */
function hasPermission(route, menuIds) {
	return menuIds.includes(route.meta.id)
}
/**
 * 判断登录后应该显示的菜单
 * @param routes 所有路由
 * @param menus 应该显示的菜单
 */
function filterAsyncRoutes(routes, menuIds) {
	const res = []
	routes.forEach(route => {
		const tmp = hasPermission(route, menuIds)
		if (tmp) {
			if (route.children) {
				/**
				 * 递归查找子目录
				 */
				route.children = filterAsyncRoutes(route.children, menuIds)
			}
			/**
			 * 有访问权限 放入结果集
			 */
			res.push(route)
		}
	})
	return res
}

const state = {
	/**
	 * 完整路由
	 */
	routes: [],
}

const mutations = {
	/**
	 * 设置路由最终需要显示的路由信息
	 */
	SET_ROUTES: (state, routes) => {
		state.routes = constantRoutes.concat(routes)
	}
}

const actions = {
	/**
	 * 生成路由 
	 */
	generateRoutes({
		commit
	}) {
		return new Promise((resolve, reject) => {
			getUserRouterInfo().then(response => {
				let accessedRoutes = filterAsyncRoutes(asyncRouterInfo, response.data)
				commit('SET_ROUTES', accessedRoutes)
				resolve(accessedRoutes)
			}).catch(error => {
				reject(error)
			})
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
